package com.kinsin.kinsinlogsystem;

import android.os.AsyncTask;
import android.util.Log;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;


// region 示例代码
// 初始化配置（建议在Application类中）
//EmailSender.getInstance().configure(
//                "smtp.example.com",  // SMTP主机
//                "587",               // 端口
//                "your@email.com",    // 发件邮箱
//                "your-password",     // 邮箱密码/授权码
//                true                 // 启用TLS
//                );

// 发送邮件
//EmailSender.getInstance().sendEmailAsync(
//        mParams.recipientEmail,
//        mParams.ccList,  // 新增抄送参数
//        title,
//        logEmailOutputInfo.toString(),
//zipFiles,
//        new EmailSender.EmailCallback() {
//    @Override
//    public void onSuccess() {
//        Log.d(TAG, "发送邮件成功");
//    }
//
//    @Override
//    public void onFailure(String error) {
//        Log.d(TAG, "发送邮件失败");
//    }
//});
// endregion 示例代码


/**
 * 邮件发送工具类
 *
 * 使用示例：
 * // 初始化配置（建议在Application类中）
 * EmailSender.getInstance().configure(
 *     "smtp.example.com",  // SMTP主机
 *     "587",               // 端口
 *     "your@email.com",    // 发件邮箱
 *     "your-password",     // 邮箱密码/授权码
 *     true                 // 启用TLS
 * );
 *
 * // 发送邮件示例
 * List<File> attachments = new ArrayList<>();
 * attachments.add(new File("/sdcard/log1.txt"));
 * attachments.add(new File("/sdcard/log2.txt"));
 *
 * EmailSender.getInstance().sendEmailAsync(
 *     "recipient@example.com",
 *     "Android Logs Report",
 *     "Log files attached",
 *     attachments,
 *     new EmailSender.EmailCallback() {
 *         @Override
 *         public void onSuccess() {
 *             Log.d(TAG, "Email sent successfully");
 *         }
 *
 *         @Override
 *         public void onFailure(String error) {
 *             Log.e(TAG, "Email send failed: " + error);
 *         }
 *     }
 * );
 */
public class EmailSender {
    private static final String TAG = "EmailSender";

    // 单例实例
    private static volatile EmailSender instance;

    // 邮件配置
    private String host;
    private String port;
    private String username;
    private String password;
    private boolean useTLS;

    public interface EmailCallback {
        void onSuccess();
        void onFailure(String error);
    }

    private EmailSender() {}

    public static EmailSender getInstance() {
        if (instance == null) {
            synchronized (EmailSender.class) {
                if (instance == null) {
                    instance = new EmailSender();
                }
            }
        }
        return instance;
    }

    /**
     * 初始化邮件服务器配置
     *
     * @param host 邮件服务器主机名
     * @param port 邮件服务器端口号
     * @param username 发件邮箱
     * @param password 邮箱密码/授权码
     * @param useTLS 是否使用TLS协议
     */
    public void configure(String host, String port,
                         String username, String password,
                         boolean useTLS) {
        this.host = host;
        this.port = port;
        this.username = username;
        this.password = password;
        this.useTLS = useTLS;
    }

    /**
     * 异步发送带附件的邮件
     *
     * @param toEmail 收件人邮箱地址
     * @param subject 邮件主题
     * @param content 邮件正文内容
     * @param attachments 附件文件列表
     * @param callback 邮件发送结果回调
     */
    public void sendEmailAsync(final String toEmail,
                               final String subject,
                               final String content,
                               final List<File> attachments,
                               final EmailCallback callback) {
        sendEmailAsync(toEmail, null, subject, content, attachments, callback);
    }

    /**
     * 异步发送带附件的邮件
     *
     * @param toEmail 收件人邮箱地址
     * @param ccList 抄送人邮箱地址
     * @param subject 邮件主题
     * @param content 邮件正文内容
     * @param attachments 附件文件列表
     * @param callback 邮件发送结果回调
     */
    public void sendEmailAsync(final String toEmail,
                              final List<String> ccList,
                              final String subject,
                              final String content,
                              final List<File> attachments,
                              final EmailCallback callback) {
        Log.e(TAG, "Send email " + toEmail + ", " + content);
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                try {
                    Log.e(TAG, "do sendEmail");
                    sendEmail(toEmail, ccList, subject, content, attachments);
                    return null;
                } catch (Exception e) {
                    Log.e(TAG, "Send email failed", e);
                    return e.getMessage();
                }
            }

            @Override
            protected void onPostExecute(String error) {
                Log.e(TAG, "onPostExecute " + error);
                if (error == null) {
                    callback.onSuccess();
                } else {
                    callback.onFailure(error);
                }
            }
        }.execute();
    }

    /**
     * 同步发送邮件（需在后台线程调用）
     *
     * @param toEmail 收件人邮箱地址
     * @param subject 邮件主题
     * @param content 邮件正文内容
     * @param attachments 附件文件列表
     * @throws MessagingException 如果邮件构建或发送失败
     * @throws UnsupportedEncodingException 如果编码不被支持
     */
    private void sendEmail(String toEmail, List<String> ccList, String subject,
                          String content, List<File> attachments)
                          throws MessagingException, UnsupportedEncodingException {
        Log.e(TAG, "in sendEmail function");
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.port", port);
        props.put("mail.smtp.auth", "true");

        if (useTLS) {
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.ssl.protocols", "TLSv1.2");
        }
        Session session = Session.getInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        Message message = new MimeMessage(session);
        message.setFrom(new InternetAddress(username, "Android Logger"));

        // 设置主送
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(toEmail));

        // 添加抄送
        if (ccList != null && !ccList.isEmpty()) {
            for (String cc : ccList) {
                message.addRecipient(Message.RecipientType.CC, new InternetAddress(cc));
            }
        }

        message.setSubject(subject);
        // 创建多部分内容
        Multipart multipart = new MimeMultipart();
        // 添加文本内容
        BodyPart messageBodyPart = new MimeBodyPart();
        messageBodyPart.setText(content);
        multipart.addBodyPart(messageBodyPart);
        // 添加附件
        if (attachments != null) {
            for (File file : attachments) {
                if (file.exists()) {
                    BodyPart attachmentBodyPart = new MimeBodyPart();
                    DataSource source = new FileDataSource(file.getAbsolutePath());
                    attachmentBodyPart.setDataHandler(new DataHandler(source));
                    attachmentBodyPart.setFileName(file.getName());
                    multipart.addBodyPart(attachmentBodyPart);
                }
            }
        }
        message.setContent(multipart);
        Transport.send(message);
    }
}